<template>
  <div class="level-setting-container">
    <!-- Header Toolbar -->
    <div class="level-header">
      <h1>等级设置</h1>
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '加载中...' : '刷新' }}
        </button>
        <button class="add-btn" @click="openAddDialog">
          添加
        </button>
      </div>
    </div>
    
    <!-- Content Area -->
    <div class="level-content">
      <!-- Loading State -->
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner large"></div>
        <p>加载中...</p>
      </div>
      
      <!-- Error State -->
      <div v-else-if="error" class="error-state">
        <div class="error-icon">⚠️</div>
        <h3>加载失败</h3>
        <p>{{ error }}</p>
        <button @click="refreshData" class="retry-btn">重试</button>
      </div>
      
      <!-- Empty State -->
      <div v-else-if="levelRules.length === 0" class="empty-state">
        <div class="empty-icon">🏆</div>
        <h3>暂无等级设置</h3>
        <p>点击上方“添加”按钮创建第一个等级设置</p>
      </div>
      
      <!-- Level Rules List -->
      <div v-else class="level-list">
        <div 
          v-for="rule in levelRules" 
          :key="rule.levelId"
          class="level-item"
        >
          <!-- Level Icon -->
          <div class="level-icon">
            <img 
              v-if="rule.uri" 
              :src="getIconPath(rule.uri)" 
              :alt="rule.levelName"
              @error="handleImageError"
            />
            <div v-else class="default-icon">🏆</div>
          </div>
          
          <!-- Level Info -->
          <div class="level-info">
            <div class="level-main">
              <div class="level-name-row">
                <h3 class="level-name">{{ rule.levelName }}</h3>
                <span class="lvl-id">LVL {{ rule.levelId }}</span>
              </div>
              <div class="level-details">
                <span class="level-id">ID: {{ rule.levelId }}</span>
                <span class="level-points">积分范围: {{ rule.minPoints }} - {{ rule.maxPoints }}</span>
                <span class="level-threshold" v-if="rule.upgradeThreshold">升级阈值: {{ rule.upgradeThreshold }}</span>
              </div>
            </div>
            <div class="level-trait" v-if="rule.coreTrait">
              <span class="trait-label">核心特质:</span>
              <span class="trait-value">{{ rule.coreTrait }}</span>
            </div>
            <div class="level-meta">
              <span class="meta-item" v-if="rule.createdAt">创建时间: {{ formatDateTime(rule.createdAt) }}</span>
              <span class="meta-item" v-if="rule.updatedAt && rule.updatedAt !== rule.createdAt">更新时间: {{ formatDateTime(rule.updatedAt) }}</span>
              <span class="meta-item" v-if="!rule.createdAt">创建时间: 未知</span>
            </div>
          </div>
          
          <!-- Operations -->
          <div class="level-operations">
            <button 
              class="op-btn update-btn" 
              @click="handleUpdate(rule)"
              title="编辑"
            >
              编辑
            </button>
            <button 
              class="op-btn toggle-btn" 
              @click="handleToggleStatus(rule)"
              title="启用/禁用"
            >
              {{ rule.enabled ? '禁用' : '启用' }}
            </button>
            <button 
              class="op-btn delete-btn" 
              @click="handleDelete(rule)"
              title="删除"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Level Footer -->
    <div class="level-footer">
      <div class="footer-content">
        <p class="footer-text">等级管理系统 - 管理和配置用户等级规则</p>
      </div>
    </div>
    
    <!-- Add Level Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeAddModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>添加等级规则</h2>
          <button class="close-btn" @click="closeAddModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitAddForm" class="level-form">
            <div class="form-group">
              <label>等级名称 *</label>
              <input 
                v-model="addForm.levelName" 
                type="text" 
                class="form-input" 
                placeholder="请输入等级名称"
                required
              />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>最小积分 *</label>
                <input 
                  v-model="addForm.minPoints" 
                  type="number" 
                  class="form-input" 
                  placeholder="0"
                  required
                />
              </div>
              <div class="form-group">
                <label>最大积分 *</label>
                <input 
                  v-model="addForm.maxPoints" 
                  type="number" 
                  class="form-input" 
                  placeholder="100"
                  required
                />
              </div>
            </div>
            <div class="form-group">
              <label>核心特质 *</label>
              <textarea 
                v-model="addForm.coreTrait" 
                class="form-textarea" 
                placeholder="请输入核心特质描述"
                rows="3"
                required
              ></textarea>
            </div>
            <div class="form-group">
              <label>图标文件名</label>
              <input 
                v-model="addForm.uri" 
                type="text" 
                class="form-input" 
                placeholder="例: level1.png"
              />
              <small class="form-hint">图标文件应放在 src/assets/images/credit 目录下</small>
            </div>
            <div class="form-group">
              <label>升级阈值</label>
              <input 
                v-model="addForm.upgradeThreshold" 
                type="text" 
                class="form-input" 
                placeholder="请输入升级要求"
              />
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeAddModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="addLoading">
                <span v-if="addLoading" class="loading-spinner"></span>
                {{ addLoading ? '添加中...' : '添加' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- Edit Level Modal -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>编辑等级规则</h2>
          <button class="close-btn" @click="closeEditModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitEditForm" class="level-form">
            <div class="form-group">
              <label>等级名称 *</label>
              <input 
                v-model="editForm.levelName" 
                type="text" 
                class="form-input" 
                placeholder="请输入等级名称"
                required
              />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>最小积分 *</label>
                <input 
                  v-model="editForm.minPoints" 
                  type="number" 
                  class="form-input" 
                  placeholder="0"
                  required
                />
              </div>
              <div class="form-group">
                <label>最大积分 *</label>
                <input 
                  v-model="editForm.maxPoints" 
                  type="number" 
                  class="form-input" 
                  placeholder="100"
                  required
                />
              </div>
            </div>
            <div class="form-group">
              <label>核心特质 *</label>
              <textarea 
                v-model="editForm.coreTrait" 
                class="form-textarea" 
                placeholder="请输入核心特质描述"
                rows="3"
                required
              ></textarea>
            </div>
            <div class="form-group">
              <label>图标文件名</label>
              <input 
                v-model="editForm.uri" 
                type="text" 
                class="form-input" 
                placeholder="例: level1.png"
              />
              <small class="form-hint">图标文件应放在 src/assets/images/credit 目录下</small>
            </div>
            <div class="form-group">
              <label>升级阈值</label>
              <input 
                v-model="editForm.upgradeThreshold" 
                type="text" 
                class="form-input" 
                placeholder="请输入升级要求"
              />
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeEditModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="editLoading">
                <span v-if="editLoading" class="loading-spinner"></span>
                {{ editLoading ? '更新中...' : '更新' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core';

// 类型扩展
declare global {
  interface Window {
    showToast?: (message: string, type: string, duration: number) => void;
  }
}

// 定义等级规则接口
interface LevelRule {
  levelId: string;
  levelName: string;
  minPoints: string;
  maxPoints: string;
  coreTrait: string;
  uri: string;
  upgradeThreshold: string;
  createdAt?: string;  // 可选，因为API响应可能不完整
  updatedAt?: string;  // 可选，因为API响应可能不完整
  enabled?: boolean;
}

// 定义API响应接口
interface ApiResponse {
  data: LevelRule[];
  msg: string;
  status: number | boolean;  // API返回数字1表示成功，或者boolean true
  code: number;
}

// 状态管理
const loading = ref(false);
const error = ref<string>('');
const levelRules = ref<LevelRule[]>([]);

// Modal 状态
const showAddModal = ref(false);
const showEditModal = ref(false);
const addLoading = ref(false);
const editLoading = ref(false);
const currentEditRule = ref<LevelRule | null>(null);

// 表单数据
const addForm = ref({
  levelName: '',
  minPoints: '',
  maxPoints: '',
  coreTrait: '',
  uri: '',
  upgradeThreshold: ''
});

const editForm = ref({
  levelId: '',
  levelName: '',
  minPoints: '',
  maxPoints: '',
  coreTrait: '',
  uri: '',
  upgradeThreshold: ''
});

// 获取等级规则数据
const fetchLevelRules = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    console.log('[DEBUG] Fetching level rules...');
    
    const response = await invoke<ApiResponse>('get_level_rules');
    console.log('[DEBUG] Response received:', response);
    
    if ((response.status === 1 || response.status === true) && (response.code === 0 || response.code === 200)) {
      levelRules.value = response.data.map(rule => ({
        levelId: rule.levelId || 'unknown',
        levelName: rule.levelName || '未知等级',
        minPoints: rule.minPoints || '0',
        maxPoints: rule.maxPoints || '0',
        coreTrait: rule.coreTrait || '无描述',
        uri: rule.uri || '',
        upgradeThreshold: rule.upgradeThreshold || '无要求',
        createdAt: rule.createdAt || new Date().toISOString(),
        updatedAt: rule.updatedAt || rule.createdAt || new Date().toISOString(),
        // 将数字 1/0 转换为 boolean
        enabled: rule.enabled === undefined ? true : Boolean(Number(rule.enabled))
      }));
      
      console.log('[DEBUG] Loaded', levelRules.value.length, 'level rules');
    } else {
      const errorMsg = response.msg || '获取等级规则失败';
      error.value = response.code === 400 
        ? `API错误 (400): ${errorMsg}` 
        : errorMsg;
    }
  } catch (err: any) {
    console.error('[ERROR] Failed to fetch level rules:', err);
    error.value = err.message || '网络请求失败';
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  console.log('刷新等级设置数据');
  fetchLevelRules();
};

// 打开新增对话框
const openAddDialog = () => {
  console.log('打开新增等级对话框');
  resetAddForm();
  showAddModal.value = true;
};

// 关闭新增对话框
const closeAddModal = () => {
  showAddModal.value = false;
  resetAddForm();
};

// 打开编辑对话框
const openEditDialog = (rule: LevelRule) => {
  console.log('打开编辑等级对话框:', rule);
  currentEditRule.value = rule;
  editForm.value = {
    levelId: rule.levelId,
    levelName: rule.levelName,
    minPoints: rule.minPoints,
    maxPoints: rule.maxPoints,
    coreTrait: rule.coreTrait,
    uri: rule.uri,
    upgradeThreshold: rule.upgradeThreshold
  };
  showEditModal.value = true;
};

// 关闭编辑对话框
const closeEditModal = () => {
  showEditModal.value = false;
  currentEditRule.value = null;
  resetEditForm();
};

// 重置新增表单
const resetAddForm = () => {
  addForm.value = {
    levelName: '',
    minPoints: '',
    maxPoints: '',
    coreTrait: '',
    uri: '',
    upgradeThreshold: ''
  };
};

// 重置编辑表单
const resetEditForm = () => {
  editForm.value = {
    levelId: '',
    levelName: '',
    minPoints: '',
    maxPoints: '',
    coreTrait: '',
    uri: '',
    upgradeThreshold: ''
  };
};

// 提交新增表单
const submitAddForm = async () => {
  if (!addForm.value.levelName || !addForm.value.minPoints || !addForm.value.maxPoints || !addForm.value.coreTrait) {
    alert('请填写所有必填字段');
    return;
  }
  
  addLoading.value = true;
  
  try {
    console.log('提交新增表单:', addForm.value);
    
    const response = await invoke<ApiResponse>('add_level_rule', {
      levelName: addForm.value.levelName,
      minPoints: addForm.value.minPoints,
      maxPoints: addForm.value.maxPoints,
      coreTrait: addForm.value.coreTrait,
      uri: addForm.value.uri,
      upgradeThreshold: addForm.value.upgradeThreshold
    });
    
    console.log('新增等级规则响应:', response);
    
    if ((response.status === 1 || response.status === true) && (response.code === 0 || response.code === 200)) {
      closeAddModal();
      await fetchLevelRules(); // 刷新列表
      
      if (window.showToast) {
        window.showToast?.('等级规则添加成功', 'success', 3000);
      }
    } else {
      const errorMsg = response.msg || '添加失败';
      console.error('添加等级规则失败:', errorMsg);
      alert(`添加失败: ${errorMsg}`);
    }
  } catch (err: any) {
    console.error('添加等级规则错误:', err);
    alert(`添加失败: ${err.message || '网络错误'}`);
  } finally {
    addLoading.value = false;
  }
};

// 提交编辑表单
const submitEditForm = async () => {
  if (!editForm.value.levelName || !editForm.value.minPoints || !editForm.value.maxPoints || !editForm.value.coreTrait) {
    alert('请填写所有必填字段');
    return;
  }
  
  editLoading.value = true;
  
  try {
    console.log('提交编辑表单:', editForm.value);
    
    const response = await invoke<ApiResponse>('update_level_rule', {
      levelId: editForm.value.levelId,
      levelName: editForm.value.levelName,
      minPoints: editForm.value.minPoints,
      maxPoints: editForm.value.maxPoints,
      coreTrait: editForm.value.coreTrait,
      uri: editForm.value.uri,
      upgradeThreshold: editForm.value.upgradeThreshold
    });
    
    console.log('更新等级规则响应:', response);
    
    if ((response.status === 1 || response.status === true) && (response.code === 0 || response.code === 200)) {
      closeEditModal();
      await fetchLevelRules(); // 刷新列表
      
      if (window.showToast) {
        window.showToast?.('等级规则更新成功', 'success', 3000);
      }
    } else {
      const errorMsg = response.msg || '更新失败';
      console.error('更新等级规则失败:', errorMsg);
      alert(`更新失败: ${errorMsg}`);
    }
  } catch (err: any) {
    console.error('更新等级规则错误:', err);
    alert(`更新失败: ${err.message || '网络错误'}`);
  } finally {
    editLoading.value = false;
  }
};

// 处理编辑操作
const handleUpdate = (rule: LevelRule) => {
  console.log('编辑等级规则:', rule);
  openEditDialog(rule);
};

// 处理启用/禁用操作
const handleToggleStatus = (rule: LevelRule) => {
  console.log('切换等级规则状态:', rule);
  // TODO: 实现状态切换功能
  if (window.showToast) {
    window.showToast?.('状态切换功能开发中...', 'info', 3000);
  }
};

// 处理删除操作
const handleDelete = (rule: LevelRule) => {
  console.log('删除等级规则:', rule);
  // TODO: 实现删除功能
  if (window.showToast) {
    window.showToast?.('删除功能开发中...', 'info', 3000);
  }
};

// 获取图标路径
const getIconPath = (uri: string): string => {
  // 如果 uri 已经是完整URL，直接返回
  if (uri.startsWith('http://') || uri.startsWith('https://') || uri.startsWith('/')) {
    return uri;
  }
  
  // 否则从 assets 目录获取
  return `/src/assets/images/credit/${uri}`;
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
  // 添加默认图标
  const defaultIcon = document.createElement('div');
  defaultIcon.className = 'default-icon';
  defaultIcon.textContent = '🏆';
  img.parentNode?.appendChild(defaultIcon);
};

// 格式化日期时间
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '未知';
  
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch {
    return dateString;
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  console.log('[DEBUG] LevelSettingPage component mounted');
  console.log('[DEBUG] Vue component environment check:', {
    isClient: typeof window !== 'undefined',
    hasTauri: typeof window !== 'undefined' && '__TAURI__' in window,
    invokeAvailable: typeof invoke === 'function'
  });
  
  // 测试基本的 Tauri 连接
  try {
    console.log('[DEBUG] Testing basic Tauri connection with greet command...');
    const greetResult = await invoke<string>('greet', { name: 'LevelSettings' });
    console.log('[DEBUG] Greet command result:', greetResult);
  } catch (greetError) {
    console.error('[ERROR] Greet command failed:', greetError);
  }
  
  // 然后调用等级规则 API
  console.log('[DEBUG] Calling fetchLevelRules...');
  await fetchLevelRules();
});
</script>

<style scoped>
/* Theme-aware styling */
.level-setting-container {
  background-color: var(--bg-primary);
  height: 100%;
  min-height: 100vh;
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Header Toolbar 样式 */
.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
  padding: 16px 20px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.level-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-btn,
.add-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.refresh-btn {
  background-color: var(--border);
  color: var(--text-primary);
}

.refresh-btn:hover:not(:disabled) {
  background-color: var(--border-hover);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.add-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.add-btn:hover {
  background-color: var(--accent-primary-hover);
}

/* Content Area 样式 */
.level-content {
  flex: 1;
  padding: 20px;
  padding-bottom: 40px;
  margin-bottom: 20px;
  overflow-y: auto;
  min-height: 0;
}

/* Loading State */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--text-secondary);
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-spinner.large {
  width: 32px;
  height: 32px;
  border-width: 3px;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Error State */
.error-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: var(--accent-danger);
}

.error-state p {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: var(--text-muted);
}

.retry-btn {
  padding: 8px 16px;
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background-color: var(--accent-primary-hover);
}

/* Empty State */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: var(--text-primary);
}

.empty-state p {
  margin: 0;
  font-size: 14px;
  color: var(--text-muted);
}

/* Level List 样式 */
.level-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.level-item {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  transition: all 0.3s ease;
}

.level-item:hover {
  border-color: var(--accent-primary);
  background-color: var(--bg-tertiary);
}

/* Level Icon */
.level-icon {
  width: 64px;
  height: 64px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-tertiary);
  border-radius: 8px;
  overflow: hidden;
}

.level-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-icon {
  font-size: 32px;
  color: var(--accent-primary);
}

/* Level Info */
.level-info {
  flex: 1;
  min-width: 0;
}

.level-main {
  margin-bottom: 12px;
}

.level-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

/* Level Name Row with LVL ID */
.level-name-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  min-height: 32px;
}

.level-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.lvl-id {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  background: linear-gradient(135deg, var(--text-primary), var(--accent-primary));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: var(--shadow-golden);
  letter-spacing: 0.5px;
}

.level-details {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 8px;
}

.level-id {
  color: var(--text-muted);
  font-size: 12px;
  font-family: monospace;
  background-color: var(--bg-tertiary);
  padding: 2px 6px;
  border-radius: 4px;
}

.level-points {
  color: var(--accent-primary);
  font-size: 14px;
  font-weight: 500;
}

.level-threshold {
  color: var(--accent-warning);
  font-size: 14px;
  font-weight: 500;
}

.level-trait {
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: var(--bg-primary);
  border-radius: 6px;
  border-left: 3px solid var(--accent-primary);
}

.trait-label {
  color: var(--text-muted);
  font-size: 12px;
  margin-right: 8px;
}

.trait-value {
  color: var(--text-primary);
  font-size: 14px;
  font-weight: 500;
}

.level-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.meta-item {
  color: var(--text-muted);
  font-size: 12px;
}

/* Level Operations */
.level-operations {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.op-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 60px;
}

.update-btn {
  background-color: var(--accent-info);
  color: var(--text-inverse);
}

.update-btn:hover {
  background-color: var(--accent-info-hover);
}

.toggle-btn {
  background-color: var(--accent-warning);
  color: var(--text-inverse);
}

.toggle-btn:hover {
  background-color: var(--accent-warning-hover);
}

.delete-btn {
  background-color: var(--accent-danger);
  color: var(--text-inverse);
}

.delete-btn:hover {
  background-color: var(--accent-danger-hover);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .level-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .level-icon {
    align-self: flex-start;
  }
  
  .level-operations {
    flex-direction: row;
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .level-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: flex-end;
  }
  
  .level-content {
    padding: 16px;
  }
  
  .level-details {
    flex-direction: column;
    gap: 8px;
  }
}

/* 滚动条样式 */
.level-content::-webkit-scrollbar {
  width: 8px;
}

.level-content::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 4px;
}

.level-content::-webkit-scrollbar-thumb {
  background: var(--accent-primary-bg);
  border-radius: 4px;
}

.level-content::-webkit-scrollbar-thumb:hover {
  background: var(--accent-primary);
}

/* Level Footer */
.level-footer {
  background-color: var(--bg-secondary);
  border-top: 1px solid var(--border);
  margin-bottom: 20px;
  padding-bottom: 16px;
  flex-shrink: 0;
}

.footer-content {
  padding: 16px 20px;
  text-align: center;
}

.footer-text {
  margin: 0;
  font-size: 14px;
  color: var(--text-muted);
  font-weight: 400;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--bg-overlay);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: var(--bg-card);
  border-radius: 12px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-modal);
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border);
  background: var(--bg-primary);
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-muted);
  font-size: 24px;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

/* Form Styles */
.level-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.form-input,
.form-textarea {
  padding: 12px 16px;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text-primary);
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: var(--shadow-focus);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.form-hint {
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid var(--border);
  margin-top: 20px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 100px;
  justify-content: center;
}

.btn-secondary {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.btn-secondary:hover {
  background: var(--bg-card);
}

.btn-primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.btn-primary:hover:not(:disabled) {
  background: var(--accent-primary-hover);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Responsive Modal */
@media (max-width: 768px) {
  .modal-content {
    margin: 0;
    max-width: 100%;
    max-height: 100%;
    border-radius: 0;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .modal-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>